<template>
	<div class="login-container flex">
		<div class="login-left">
			<div class="login-left-logo">
				<img :src="logoMini" />
				<div class="login-left-logo-text">
					<span>{{ getThemeConfig.globalViceTitle }}</span>
					<span class="login-left-logo-text-msg">{{ getThemeConfig.globalViceTitleMsg }}</span>
				</div>
			</div>
			<div class="login-left-img">
				<img :src="loginMain" />
			</div>
			<img :src="loginBg" class="login-left-waves" />
		</div>
		<div class="login-right flex">
			<div class="login-right-warp flex-margin">
				<span class="login-right-warp-one"></span>
				<span class="login-right-warp-two"></span>
				<div class="login-right-warp-mian">
					<div class="login-right-warp-main-title" :class="state.ruleForm.is_mobile === 1 ? 'is_mobile' : ''">{{ getThemeConfig.globalTitle }} 欢迎您！</div>
					<div class="login-right-warp-main-form">
						<div v-if="!state.isScan">
							<el-tabs v-model="state.tabsActiveName" :stretch="true">
								<el-tab-pane :label="$t('message.label.one1')" name="account">
									<el-form size="large" class="login-content-form" @keyup.native.enter="keyDown">
										<el-form-item class="login-animation1">
											<el-input text :placeholder="$t('message.account.accountPlaceholder1')" v-model="state.ruleForm.username" clearable autocomplete="off">
												<template #prefix>
													<el-icon class="el-input__icon"><ele-User /></el-icon>
												</template>
											</el-input>
										</el-form-item>
										<el-form-item class="login-animation2">
											<el-input
												:type="state.isShowPassword ? 'text' : 'password'"
												:placeholder="$t('message.account.accountPlaceholder2')"
												v-model="state.ruleForm.password"
												autocomplete="off"
												show-password
											>
												<template #prefix>
													<el-icon class="el-input__icon"><ele-Unlock /></el-icon>
												</template>
<!--												<template #suffix>-->
<!--													<i-->
<!--														class="iconfont el-input__icon login-content-password"-->
<!--														:class="state.isShowPassword ? 'icon-yincangmima' : 'icon-xianshimima'"-->
<!--														@click="state.isShowPassword = !state.isShowPassword"-->
<!--													>-->
<!--													</i>-->
<!--												</template>-->
											</el-input>
										</el-form-item>
										<el-form-item class="login-animation3" v-if="state.ruleForm.is_captcha === 1">
											<el-col :span="15">
												<el-input
													text
													maxlength="4"
													:placeholder="$t('message.account.accountPlaceholder3')"
													v-model="state.ruleForm.captcha"
													clearable
													autocomplete="off"
												>
													<template #prefix>
														<el-icon class="el-input__icon"><ele-Position /></el-icon>
													</template>
												</el-input>
											</el-col>
											<el-col :span="1"></el-col>
											<el-col :span="8" style="margin-top: 17px">
												<el-image :src="state.verifyCode"  @click="refreshCaptcha"></el-image>
											</el-col>
										</el-form-item>
										<el-form-item class="login-animation2" v-if="state.ruleForm.is_mobile === 1">
											<el-col :span="15">
												<el-input text maxlength="4" placeholder="请输入验证码" v-model="state.ruleForm.phone_code" clearable autocomplete="off">
													<template #prefix>
														<el-icon class="el-input__icon"><ele-Position /></el-icon>
													</template>
												</el-input>
											</el-col>
											<el-col :span="1"></el-col>
											<el-col :span="8">
												<el-button v-waves class="login-content-code" v-if="state.captchaData.flag === 0" @click="sendCaptcha">{{ state.captchaData.btnTip }}</el-button>
												<el-button v-waves class="login-content-code" v-if="state.captchaData.flag === 1" style="background: #8c939d; color: #f1f1f1;">{{ state.captchaData.btnTip }}</el-button>
											</el-col>
										</el-form-item>
										<el-form-item class="login-animation4">
											<el-button type="primary" class="login-content-submit" round v-waves @click="onSignIn" :loading="state.loading.signIn">
												<span>{{ $t('message.account.accountBtnText') }}</span>
											</el-button>
										</el-form-item>
									</el-form>
								</el-tab-pane>
							</el-tabs>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts" name="loginIndex">
import { onMounted, reactive, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { initFrontEndControlRoutes } from '/@/router/frontEnd';
import { initBackEndControlRoutes } from '/@/router/backEnd';
import { Session } from '/@/utils/storage';
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
import { NextLoading } from '/@/utils/loading';
import logoMini from '/@/assets/logo-mini.svg';
import loginMain from '/@/assets/login-main.svg';
import loginBg from '/@/assets/login-bg.svg';
import { formatAxis } from '/@/utils/formatTime';
import {useLoginApi} from "/@/api/common/login";


// 定义变量内容
const { t } = useI18n();
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const route = useRoute();
const router = useRouter();
const state = reactive({
	tabsActiveName: 'account',
	isScan: false,
	isShowPassword: false,
	ruleForm: {
		username: '',
		password: '',
		is_captcha: 0,
		captcha: '',
		captcha_key: '',
		is_mobile: 0,
		phone_code: '',
	},
	verifyCode: '',
	captchaData: {
		btnTip: '发送验证码', // 验证码提示
		time: 60, // 时长
		flag: 0, // 是否点击
	},
	loading: {
		signIn: false,
	},
});

// 获取布局配置信息
const getThemeConfig = computed(() => {
	return themeConfig.value;
});

//点击回车键登录
const keyDown = (e: any) => {
	if (e.keyCode === 13 || e.keyCode === 100) {
		onSignIn()
	}
}

// 刷新验证码
const refreshCaptcha = () => {
	useLoginApi().getLoginCode().then(res => {
		state.verifyCode = res.data.img;
		state.ruleForm.captcha_key = res.data.certificate;
	});
};

// 发送验证码
const sendCaptcha = async () => {
	if (!state.ruleForm.username) {
		ElMessage.warning('请输入手机号');
		return false;
	}
	if (state.captchaData.flag === 0) {
		state.captchaData.flag = 1;
		let time = state.captchaData.time;

		try {
			await useLoginApi().getPhoneCode({phone: state.ruleForm.username}).then((res: any) => {
				if (res.code === 200) {
					ElMessage.success(res.message)
					state.ruleForm.phone_code = res?.data?.phone_code;

					const m = setInterval(() => {

						state.captchaData.btnTip = --time + '秒后重试';

						if (time <= 0) {
							clearInterval(m);
							state.captchaData.btnTip = '发送验证码';
							state.captchaData.flag = 0;
						}
					}, 1000);
				} else {
					ElMessage.error(res.message)
					state.captchaData.flag = 0;
				}
			})
		} catch (e) {
			state.captchaData.flag = 0;
		}
	}
};

// 时间获取
const currentTime = computed(() => {
	return formatAxis(new Date());
});
// 登录
const onSignIn = async () => {
	if (!state.ruleForm.username) {
		ElMessage.warning('请输入账号');
		return false;
	}
	if (!state.ruleForm.password) {
		ElMessage.warning('请输入密码');
		return false;
	}
	if (state.ruleForm.is_captcha && !state.ruleForm.captcha) {
		ElMessage.warning('请输入验证码');
		return false;
	}
	if (state.ruleForm.is_mobile && !state.ruleForm.phone_code) {
		ElMessage.warning('请输入手机验证码');
		return false;
	}
	state.loading.signIn = true;
	const res = await useLoginApi().signIn(state.ruleForm)
	if (res.code === 200) {
		Session.set('token', res.data.token);
		Session.set('userInfo', res.data.userInfo);
	} else {
		state.ruleForm.is_captcha = res.data.is_captcha;
		state.ruleForm.is_mobile = res.data.is_mobile;
		state.loading.signIn = false;
		await getLoginData();
		return;
	}

	// 存储 token 到浏览器缓存
	// Session.set('token', Math.random().toString(36).substr(0));
	// 模拟数据，对接接口时，记得删除多余代码及对应依赖的引入。用于 `/src/stores/userInfo.ts` 中不同用户登录判断（模拟数据）
	// Cookies.set('username', state.ruleForm.username);
	if (!themeConfig.value.isRequestRoutes) {
		// 前端控制路由，2、请注意执行顺序
		const isNoPower = await initFrontEndControlRoutes();
		signInSuccess(isNoPower);
	} else {
		// 模拟后端控制路由，isRequestRoutes 为 true，则开启后端控制路由
		// 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
		const isNoPower = await initBackEndControlRoutes();
		// 执行完 initBackEndControlRoutes，再执行 signInSuccess
		signInSuccess(isNoPower);
	}
};
// 登录成功后的跳转
const signInSuccess = (isNoPower: boolean | undefined) => {
	if (isNoPower) {
		ElMessage.warning('抱歉，您没有登录权限');
		Session.clear();
	} else {
		// 初始化登录成功时间问候语
		let currentTimeInfo = currentTime.value;
		// 登录成功，跳到转首页
		// 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
		if (route.query?.redirect) {
			router.push({
				path: <string>route.query?.redirect,
				query: Object.keys(<string>route.query?.params).length > 0 ? JSON.parse(<string>route.query?.params) : '',
			});
		} else {
			router.push('/');
		}
		// 登录成功提示
		const signInText = t('message.signInText');
		ElMessage.success(`${currentTimeInfo}，${signInText}`);
		// 添加 loading，防止第一次进入界面时出现短暂空白
		NextLoading.start();
	}
	state.loading.signIn = false;
};

// 获取登录数据
const getLoginData = async () => {
	refreshCaptcha();
	useLoginApi().getLoginData().then(res => {
		state.ruleForm.is_captcha = res.data.is_captcha;
		state.ruleForm.is_mobile = res.data.is_mobile;
	});
}

// 页面加载时
onMounted(() => {
	getLoginData();
	NextLoading.done();
});
</script>

<style scoped>
.el-tabs__nav {
	display: block !important;
	float: none !important;
}
</style>

<style scoped lang="scss">
.login-container {
	height: 100%;
	background: var(--el-color-white);
	.login-left {
		flex: 1;
		position: relative;
		background-color: rgba(211, 239, 255, 1);
		margin-right: 100px;
		.login-left-logo {
			display: flex;
			align-items: center;
			position: absolute;
			top: 50px;
			left: 80px;
			z-index: 1;
			animation: logoAnimation 0.3s ease;
			img {
				width: 52px;
				height: 52px;
			}
			.login-left-logo-text {
				display: flex;
				flex-direction: column;
				span {
					margin-left: 10px;
					font-size: 28px;
					color: #26a59a;
				}
				.login-left-logo-text-msg {
					font-size: 12px;
					color: #32a99e;
				}
			}
		}
		.login-left-img {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			width: 100%;
			height: 52%;
			img {
				width: 100%;
				height: 100%;
				animation: error-num 0.6s ease;
			}
		}
		.login-left-waves {
			position: absolute;
			top: 0;
			right: -100px;
		}
	}
	.login-right {
		width: 700px;
		.login-right-warp {
			border: 1px solid var(--el-color-primary-light-3);
			border-radius: 3px;
			width: 500px;
			height: 500px;
			position: relative;
			overflow: hidden;
			background-color: var(--el-color-white);
			.login-right-warp-one,
			.login-right-warp-two {
				position: absolute;
				display: block;
				width: inherit;
				height: inherit;
				&::before,
				&::after {
					content: '';
					position: absolute;
					z-index: 1;
				}
			}
			.login-right-warp-one {
				&::before {
					filter: hue-rotate(0deg);
					top: 0px;
					left: 0;
					width: 100%;
					height: 3px;
					background: linear-gradient(90deg, transparent, var(--el-color-primary));
					animation: loginLeft 3s linear infinite;
				}
				&::after {
					filter: hue-rotate(60deg);
					top: -100%;
					right: 2px;
					width: 3px;
					height: 100%;
					background: linear-gradient(180deg, transparent, var(--el-color-primary));
					animation: loginTop 3s linear infinite;
					animation-delay: 0.7s;
				}
			}
			.login-right-warp-two {
				&::before {
					filter: hue-rotate(120deg);
					bottom: 2px;
					right: -100%;
					width: 100%;
					height: 3px;
					background: linear-gradient(270deg, transparent, var(--el-color-primary));
					animation: loginRight 3s linear infinite;
					animation-delay: 1.4s;
				}
				&::after {
					filter: hue-rotate(300deg);
					bottom: -100%;
					left: 0px;
					width: 3px;
					height: 100%;
					background: linear-gradient(360deg, transparent, var(--el-color-primary));
					animation: loginBottom 3s linear infinite;
					animation-delay: 2.1s;
				}
			}
			.login-right-warp-mian {
				display: flex;
				flex-direction: column;
				height: 100%;
				.login-right-warp-main-title {
					height: 130px;
					line-height: 130px;
					font-size: 27px;
					text-align: center;
					letter-spacing: 3px;
					animation: logoAnimation 0.3s ease;
					animation-delay: 0.3s;
					color: var(--el-text-color-primary);
				}
				.is_mobile {
					height: 72px !important;
					line-height: 72px !important;
				}
				.login-right-warp-main-form {
					flex: 1;
					padding: 0 50px 50px;
					.login-content-form {
						margin-top: 20px;
						@for $i from 1 through 4 {
							.login-animation#{$i} {
								opacity: 0;
								animation-name: error-num;
								animation-duration: 0.5s;
								animation-fill-mode: forwards;
								animation-delay: calc($i/10) + s;
							}
						}
						.login-content-password {
							display: inline-block;
							width: 20px;
							cursor: pointer;
							&:hover {
								color: #909399;
							}
						}
						.login-content-code {
							width: 100%;
							padding: 0;
							font-weight: bold;
							letter-spacing: 5px;
						}
						.login-content-submit {
							width: 100%;
							letter-spacing: 2px;
							font-weight: 300;
							margin-top: 15px;
						}
					}
					.login-content-main-sacn {
						position: absolute;
						top: 0;
						right: 0;
						width: 50px;
						height: 50px;
						overflow: hidden;
						cursor: pointer;
						transition: all ease 0.3s;
						color: var(--el-color-primary);
						&-delta {
							position: absolute;
							width: 35px;
							height: 70px;
							z-index: 2;
							top: 2px;
							right: 21px;
							background: var(--el-color-white);
							transform: rotate(-45deg);
						}
						&:hover {
							opacity: 1;
							transition: all ease 0.3s;
							color: var(--el-color-primary) !important;
						}
						i {
							width: 47px;
							height: 50px;
							display: inline-block;
							font-size: 48px;
							position: absolute;
							right: 1px;
							top: 0px;
						}
					}
				}
			}
		}
	}
}
</style>
